// 时间分组工具函数
export interface TimeGroup {
  label: string
  key: string
  sessions: any[]
  icon?: string
}

export const groupSessionsByTime = (sessions: any[]): TimeGroup[] => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
  const weekAgo = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
  const monthAgo = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)

  const groups: TimeGroup[] = [
    { label: '今天', key: 'today', sessions: [], icon: '📅' },
    { label: '昨天', key: 'yesterday', sessions: [], icon: '📋' },
    { label: '本周', key: 'thisWeek', sessions: [], icon: '📊' },
    { label: '本月', key: 'thisMonth', sessions: [], icon: '📁' },
    { label: '更早', key: 'earlier', sessions: [], icon: '🗂️' }
  ]

  sessions.forEach(session => {
    const sessionDate = new Date(session.updated_at)
    
    if (sessionDate >= today) {
      groups[0].sessions.push(session)
    } else if (sessionDate >= yesterday) {
      groups[1].sessions.push(session)
    } else if (sessionDate >= weekAgo) {
      groups[2].sessions.push(session)
    } else if (sessionDate >= monthAgo) {
      groups[3].sessions.push(session)
    } else {
      groups[4].sessions.push(session)
    }
  })

  // 过滤掉空分组，保持非空分组
  return groups.filter(group => group.sessions.length > 0)
}

export const formatRelativeTime = (date: Date): string => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return date.toLocaleDateString('zh-CN', {
    month: 'short',
    day: 'numeric'
  })
}